//
//  OAuthController.swift
//  MyWeiBo
//
//  Created by mac on 15/3/2.
//  Copyright (c) 2015年 gpr. All rights reserved.
//

import UIKit
//import SimpleNetWork

class OAuthController: UIViewController {
    let oauthURLString = "https://api.weibo.com/oauth2/authorize"
    let TOKEN_BASE_ADDR = "https://api.weibo.com/oauth2/access_token"
    let API_PREFIX = "https://api.weibo.com"
    let CODE_TYPE: NSString! = "code="
    let GRANT_TYPE = "authorization_code"
    var relaoad: Bool = false
    
    @IBOutlet weak var webView: UIWebView!
    
    // MARK: 快速创建的方法
    class func oAuthController() -> UIViewController {
        let storyBoard = UIStoryboard(name: "OAuthController", bundle: nil)
        let vc = storyBoard.instantiateInitialViewController() as! UIViewController
        return vc
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.webView.delegate = self
        self.startOAuth()
    }
    
    // MARK: 开始认证操作
    func startOAuth() {
        let ursString = oauthURLString + "?client_id=" + WB_APP_KEY + "&redirect_uri=" + WB_REDIRECT_ADDR
        self.webView.loadRequest(NSURLRequest(URL: NSURL(string: ursString)!))
    }

    // MARK: 根据 url 地址判断该请求是否允许加载
    func isLoadURL(url: NSURL) -> (isLoad: Bool,code: String?, reload: Bool) {
        if url.absoluteString!.hasPrefix(API_PREFIX) {
            return (true,nil,false)
        } else if url.absoluteString!.hasPrefix(WB_REDIRECT_ADDR) {
            let query: NSString = url.query!
            if query.hasPrefix(CODE_TYPE as String) {
                let code = query.substringFromIndex(CODE_TYPE.length)
                return (false,code,false)
            } else {
                SVProgressHUD.showErrorWithStatus("你真的要取消么?", maskType: .Gradient)
                self.relaoad = true
                return (false,nil,true)
            }
        }
        return (false,nil,false)
    }
    
    func getTokenWithCode(code: String) {
        let request = OAuthRequest()
        request.client_id = WB_APP_KEY
        request.client_secret = WB_APP_SECRET
        request.grant_type = GRANT_TYPE
        request.code = code
        request.redirect_uri = WB_REDIRECT_ADDR
        OAuthNetWorkTools.requestAccountWithOAuthRequest(request, complete: { (account, error) -> () in
            if AccountTool.saveAccount(account!) {
                self.switchToHomeVC()
            } else {
                SVProgressHUD.dismiss()
                SVProgressHUD.showErrorWithStatus("请求失败", maskType: .Gradient)
            }
            
        })
    }
    
    // MARK: 跳转到主页
    func switchToHomeVC() {
        let vc = WBTabBarViewController.wbTabBarViewController()
        UIApplication.sharedApplication().keyWindow?.rootViewController = vc
    }
}

// MARK: 网页请求代理
extension OAuthController: UIWebViewDelegate {
    // MARK: 开始加载
    func webViewDidStartLoad(webView: UIWebView){
        if !self.relaoad {
            SVProgressHUD.showInfoWithStatus("正在帮你加载中,请稍等...", maskType: .Gradient)
        }
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let isLoad = self.isLoadURL(request.URL!)
        if isLoad.code != nil {
            // 获取token
            self.getTokenWithCode(isLoad.code!)
        }
        if isLoad.reload {
            self.startOAuth()
        }
        return isLoad.isLoad
    }
    
    // MARK: 加载完毕
    func webViewDidFinishLoad(webView: UIWebView){
        SVProgressHUD.dismiss()
    }
    
    // MARK: 加载出错
    func webView(webView: UIWebView, didFailLoadWithError error: NSError){
//        println("error\(NSThread.currentThread())")
//        SVProgressHUD.dismiss()
//        SVProgressHUD.showErrorWithStatus("请求失败", maskType: .Gradient)
    }
}
